package mqttClient

import (
	"gitee.com/yuyuaa/easyGoTool.git/gofunc"
	"gitee.com/yuyuaa/wensGoMqtt.git/common"
	"gitee.com/yuyuaa/wensGoMqtt.git/model"
	"log"
	"strings"
	"time"
)

type Client struct {
	Config          *Config
	DevId           string      //传入的设备id
	DevType         MqttDevType //设备类型
	Topic           topicList
	httpBridgePort  string //http转发到的端口
	IsOnline        bool   //是否外网是通的
	hasfirstConnect bool   //第一次是否已经连上了
	Base            *model.BaseLink
}

type topicList struct {
	StateTopic       string `json:"state_topic"`        //发布的状态的topic
	ApiTopic         string `json:"api_topic"`          //调用api的topic
	ApiResponseTopic string `json:"api_response_topic"` //调用api后返回的topic
}

func NewConfig(configUrl string) (error,*Config) {
	_c:=new(Config)
	_c.Mqtt.Addr = common.Const_host
	_c.Mqtt.APISub = common.Const_apisub
	_c.Mqtt.StatePub = common.Const_statepub
	_c.Mqtt.RespTail = common.Const_resptail
	_c.Mqtt.TcpBridgeCtrl = common.Const_tcpbridgectrl
	_c.Mqtt.TcpSub = common.Const_tcpsub
	//传入配置参数
	err := _c.SetUseFile(_c, configUrl)
	if err != nil {
		return err,nil
	}
	return nil,_c
}

//传入一份json格式的配置文件
func (self *Client) SetUp(config *Config, devId string, httpPort string, devType MqttDevType) error {
	self.Config = config
	self.Base = new(model.BaseLink)
	self.DevId = devId
	self.httpBridgePort = httpPort
	self.DevType = devType
	//查看下是否已经有uid了没有就通过接口查一下
	if self.Config.Mqtt.ClientId == "" {
		err := self.CheckHasRegist()
		if err != nil {
			log.Println(err, "不能查到uid")
		}
	}
	//查完后一直等待uid不为空,必须保证了uid不为空的情况才进行init
	if self.Config.Mqtt.ClientId != "" {
		self.mqttinit()
		return nil
	} else {
		//判断能否连接到外网
		ipfunc := gofunc.IpFunc{}
		err := ipfunc.Ping("www.baidu.com")
		if err != nil {
			self.IsOnline = false
		} else {
			self.IsOnline = true
		}
		//一直等待uid为非空再进行mqtt初始化
		go func() {
			for {
				time.Sleep(3 * time.Second)
				log.Println("判断uid是否已经为非空")
				if self.Config.Mqtt.ClientId != "" {
					self.mqttinit()
					return
				}
			}
		}()
	}
	return nil
}

//向mqtt发布设备状态
func (self *Client) StatePub(msg string, ty StatePublishType) error {
	//topic := "/{{clientId}}/state/{type}"
	topic := self.Config.Mqtt.StatePub + "/" + string(ty) //"/{{clientId}}/state/envctrl"
	clientId, _, _ := self.GetConnectInfoByUid()
	statepub := strings.Replace(topic, "{{clientId}}", clientId, -1)
	err := self.Base.MqttPub(statepub, []byte(msg))
	if err != nil {
		return err
	}
	return nil
}

//定义自身发送的频道
func (self *Client) StateSub(callback func(msg string)) error {
	topic := self.Config.Mqtt.StatePub
	clientId, _, _ := self.GetConnectInfoByUid()
	statepub := strings.Replace(topic, "{{clientId}}", clientId, -1)
	err := self.Base.MqttSub(statepub, func(topic string, tmsg []byte) {
		callback(string(tmsg))
	})
	if err != nil {
		return err
	}
	return nil
}
